/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.util.*;

public abstract class Servlet1 extends Servlet0
{
	//versão 1, atualizar sempre que mexer no servlet
	private static final long serialVersionUID = 1L;
	protected String id;
    private Map<String,String> map;

    protected abstract String dispatch(String action) throws Exception;

    protected String handle() throws Exception
    {
    	// Cuida das requisições que não requerem autenticação.
    	try {
    		int auth = Integer.parseInt(param("auth"));
    		if (auth == 0) {
    			map = new HashMap<String, String>();
    			map.put("idCampaign", req.getParameter("idCampaign"));  // null se o parâmetro está ausente.
    			String ret = dispatch(param("action"));
    			if (ret != null) return ret;
    		}
    	} catch (Exception e) {	}
    	
        id = param("id");
        System.out.println("id: "+id);

        map = Auth.decode(id, param("msg"));

        String action = arg("action");
        System.out.println(action + ":");

        String ret = dispatch(action);
        System.out.println(ret);
        if (ret == null) throw new Exception("Invalid action");
        
        return ret;
    }

    protected String argn(String name)
    {
        return map.get(name);
    }

    protected String arg(String name) throws Exception
    {
        String ret = map.get(name);
        System.out.println(name+" "+ret);
        if (ret == null) throw new Exception("Missing arg: " + name);
        return ret;
    }

    protected double argd(String name) throws Exception
    {
        try {
            return Double.parseDouble(arg(name));
        } catch (NumberFormatException e) {
            throw new Exception("Invalid number: " + name + ", "+arg(name));
        }
    }
}
